import UIKit

class TF_ChatRecord: UIView ,TF_ChatRecordCellDelegate, UITableViewDelegate, UITableViewDataSource{

    @objc public let tableView = UITableView()
    @objc public let scrollView = UIScrollView()
    @objc public let dataSource = NSMutableArray()
    @objc public var cellWidth:CGFloat = 0
    /** 代理对象 */
    @objc public weak var delegate : TF_ChatRecordDelegate?
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.cellWidth = TalkfunSharedTools.getMainScreen().size.width - 10 - 103
        self.addSubview(self.scrollView)
        
        self.tableView.backgroundColor = UIColor.clear
        self.tableView.delegate = self
        self.tableView.dataSource = self
        self.scrollView.addSubview(self.tableView)
        self.tableView.separatorStyle = .none
        self.tableView.separatorInset = .zero;
        self.tableView.register(TF_ChatRecordCell.self, forCellReuseIdentifier: "TF_ChatRecordCell")
        self.tableView.register(TF_LivingBroadcastCell.self, forCellReuseIdentifier: "TF_LivingBroadcastCell")
    }
    

    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataSource.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
    let model = self.dataSource[indexPath.row] as! TF_LivingChatData
        
        if (model.isBroadcast == false) {
        let cell = tableView.dequeueReusableCell(withIdentifier: "TF_ChatRecordCell") as! TF_ChatRecordCell
            cell.delegate = self
            cell.cellWidth = self.cellWidth;
            cell.model = model
            cell.selectionStyle = .none;

            return cell
        }else{
            let cell = tableView.dequeueReusableCell(withIdentifier: "TF_LivingBroadcastCell") as! TF_LivingBroadcastCell
            cell.selectionStyle = .none;
            let msg = "(14:22)公共广播：" + model.msg
           
            
            let attrsSize: CGSize = msg.size(withAttributes: [NSAttributedString.Key.font: UIFont.PingFang(size: 16)])
            
            
            var msgbackgroundColorViewWidth:CGFloat = self.frame.size.width - 15 - 9 - ( 10 + 15 + 95 + 12 )
            
            if (attrsSize.width < msgbackgroundColorViewWidth ) {
                msgbackgroundColorViewWidth = attrsSize.width + 5
            }
            cell.msgbackgroundColorView.frame = CGRect(x: 15, y: 9 - 5 - 2, width: msgbackgroundColorViewWidth+15+15, height: self.getCellThirdHegiht(model: model).height-5-5)
            

            cell.msgbackgroundColorView.layer.cornerRadius = 21
            
            cell.msg.frame = CGRect(x: 15+15, y: 9-5-2, width: msgbackgroundColorViewWidth, height: self.getCellThirdHegiht(model: model).height-5-5)

        
            let  currentDateStr = TalkfunSharedTools.getTimestamp(mStr: model.time as NSString)
        
            let timeStr:NSString = "(14:22)公共广播："
        
            //将字符串中" 14:22" 全部替换成 新的
           //let  netStr = ["(14:22)公共广播："
            timeStr.replacingOccurrences(of:"14:22" , with:currentDateStr as String )
            
            
            let string:NSString = ((timeStr as NSString) as String) + model.msg as NSString
          
            //时间
            let fontAttributeNameStr = NSMutableAttributedString.init(string: string as String)
            let font16 = UIFont.PingFang(size: 13)
            let attr16: [NSAttributedString.Key : Any] = [.font: font16 as Any,]
            //(14:22)系统消息： 的字体
            fontAttributeNameStr.addAttributes(attr16, range: NSRange(location:0, length: string.length ))
          
            //(14:22)系统消息： 的颜色
            fontAttributeNameStr.addAttribute(.foregroundColor, value: UIColor(red: 255/255.0, green: 243/255.0, blue: 70/255.0, alpha: 1.0), range: NSRange(location: 0, length:  string.length))

        
            //msg 的颜色
            let msg33:NSString = model.msg as NSString
            fontAttributeNameStr.addAttribute(.foregroundColor, value: UIColor(red: 255/255.0, green: 243/255.0, blue: 70/255.0, alpha: 1.0), range: NSRange(location: timeStr.length, length:  msg33.length))
            
        

            cell.msg.attributedText = fontAttributeNameStr;
            return cell
        }
       
        
       
    }
    // 设置cell高度
      func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
          return self.getCellHeight(row: indexPath.row)
      }
  @objc public func getCellHeight(row:Int)->CGFloat
    {
        let model = self.dataSource[row] as! TF_LivingChatData
        if (model.isBroadcast) {
            //广播
            return  self.getCellThirdHegiht(model: model).height
        }
        else{
            //聊天
            
            return self.getCellChatHegiht(model: model)
          
        }
    }
    
    func getCellChatHegiht(model:TF_LivingChatData)->CGFloat
    {
        let imageURL:NSString = model.imageURL as NSString
        
        if (imageURL.length>0) {
    //        NSLog(@"图片-----------");
            var imageHight:CGFloat = 104
            
            let backgroundColorViewWidth:CGFloat =  self.cellWidth - 5 - 30 - 10
            
            if ((model.image) != nil&&model.image.size.width >= backgroundColorViewWidth ) {

        
                 let proportion:CGFloat = model.image.size.width/backgroundColorViewWidth ;
                 
                  imageHight = model.image.size.height/proportion;
             }
             else if((model.image) != nil){
                 imageHight =  model.image.size.height
             }
            //12名字是到图片的间距   24 是图片到与底边的间距
            let height:CGFloat = imageHight + 36.5 + 12 + 12 + 5
            
          return height;
        }

        
        var msg:NSString = model.nickname + "：" as NSString
        
        for i in stride(from: 0, to: model.replyList.count ,by: 1) {
             let reply = model.replyList[i] as! TFChatReply
   
            msg = (msg as String) + "" as NSString
            msg = (msg as String) + reply.nickname as NSString
            msg = (msg as String) + " " as NSString

        }
        
        msg = (msg as String) + model.msg as NSString
      
     let attributedText = TalkfunSharedTools.getAttributedText(msg as String, fontSize: UIFont.PingFang(size: 16), foregroundColor: UIColor.white)
          
      let contentDict = TalkfunSharedTools.getSizeLabel(labelString: attributedText, labelWidth:self.cellWidth-42-12, labelfont: UIFont.PingFang(size: 16))
        
        
        if (contentDict.height + 10 + 10 + 5 < 42) {
           return 42
        }
        return contentDict.height + 10 + 10 + 5
    }
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func layoutSubviews() {
        super.layoutSubviews()
        
        self.scrollView.frame = self.bounds;
        self.scrollView.contentSize = CGSize(width: 0, height: self.bounds.size.height + 10)
        
    }
    
    func getCellThirdHegiht(model:TF_LivingChatData)->CGSize
    {
        let msg = "(14:22)公共广播：" + model.msg
          
       let string = TalkfunSharedTools.getAttributedText(msg, fontSize: UIFont.PingFang(size: 16), foregroundColor: UIColor.white)
          
        var rect = TalkfunSharedTools.getSizeLabel(labelString: string, labelWidth:self.frame.size.width-15-9-(10+15+95+12), labelfont: UIFont.PingFang(size: 16))
        
        
        rect.height = rect.height+9+9+5+5
        // 5 +5 是cell 间距
        return rect;
    }
    
    @objc public func tableViewReloadData()
    {

        self.tableView.reloadData()
        if (self.dataSource.count > 0) {
            let indexpath = NSIndexPath.init(row: self.dataSource.count - 1, section: 0)
            
            self.tableView.scrollToRow(at: indexpath as IndexPath, at: .bottom, animated: true)
         
            
//            [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.dataSource.count - 1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
        }
    }
    //cell的代理
    func fullScreenPicture(_ model: TF_LivingChatData) {
        if self.delegate != nil && (self.delegate?.responds(to: #selector(TF_ChatRecordCellDelegate.fullScreenPicture(_:))))!{

            self.delegate?.fullScreenPicture(model)
        }
    }
    // 选中cell后执行此方法
        func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
            
            
            
//            print(indexPath.row)
        }
}


@objc protocol TF_ChatRecordDelegate : NSObjectProtocol {
    //全屏图片                                图片序列号
   @objc func fullScreenPicture(_ model : TF_LivingChatData)
}
